package org.an.proj.contacts.net.service;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.an.proj.contacts.tool.gson.Ignore;

/**
 * module 转 map
 * ignore field use {@link Ignore}
 */
public class BeanToMapUtil {
  public static Map<String, String> getBodyParams(Object obj) {
    Map<String, String> params = new HashMap<String, String>();
    if (obj != null) {
      Class<?> cls = obj.getClass();
      for (int i = 0; i < cls.getFields().length; i++) {
        try {
          Field field = cls.getFields()[i];
          // getAnnotations 该字段的所有注解，getDeclaredAnnotations 忽略集成的注解
          if (field.isAnnotationPresent(Ignore.class)) {
            Ignore ignore = field.getAnnotation(Ignore.class);
            if (ignore.ignoreTransform()) continue;
          }

          Object fieldValue = field.get(obj);
          if (fieldValue != null) {
            if (fieldValue instanceof List) {
              addListFromParams(params, field.getName(), fieldValue);
            } else {
              params.put(field.getName(), fieldValue.toString());
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
          continue;
        }
      }
    }

    return params;
  }

  private static void addListFromParams(Map<String, String> params, String listFeildName,
      Object listData) {
    @SuppressWarnings("unchecked") List<Object> value = (List<Object>) listData;
    for (int j = 0; j < value.size(); j++) {
      Object itemObj = value.get(j);
      Class<?> item = itemObj.getClass();
      for (int z = 0; z < item.getFields().length; z++) {
        try {
          Field itemField = item.getFields()[z];
          Object itemFeildValue = itemField.get(itemObj);
          if (itemFeildValue != null) {
            if (itemFeildValue instanceof List) {
              addListFromParams(params, listFeildName + "[" + j + "]." +
                  itemField.getName(), itemFeildValue);
            } else {
              params.put(listFeildName + "[" + j + "]." +
                  itemField.getName(), itemFeildValue.toString());
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
          continue;
        }
      }
    }
  }
}
